<?php

namespace backend\modules\bonus\controllers;

use Yii;
use common\models\base\SearchModel;
use common\traits\MerchantCurd;
use common\models\member\Member;
use common\enums\StatusEnum;
use backend\controllers\BaseController;
use common\models\bonus\Bonus;
use common\models\bonus\BonusQi;
use common\models\bonus\BonusQiMember;
use common\models\bonus\BonusDp;
use common\models\bonus\BonusXf;
use common\models\bonus\BonusYear;
use backend\modules\bonus\forms\DpForm;
use common\models\bonus\BonusFl;
use backend\modules\bonus\forms\FlForm;
use common\models\bonus\BonusDj;
use common\helpers\ExcelHelper;
use common\enums\BonusEnum;

class BsController extends BaseController
{
    use MerchantCurd;

    /**
     * @var \yii\db\ActiveRecord
     */
    public $modelClass = BonusQi::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => BonusQi::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query;

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionMember($qi)
    {
        $qi = BonusQi::findOne($qi);
        $searchModel = new SearchModel([
            'model' => BonusQiMember::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['pid'=>$qi->id]);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'qi' => $qi,
        ]);
    }

    public function actionMemberData($id)
    {
        $model = BonusQiMember::findOne($id);
        $searchModel = new SearchModel([
            'model' => Bonus::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['bonus_id'=>$model->id]);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'model' => $model,
        ]);
    }

    public function actionEnd($id)
    {
        $update = BonusQi::updateAll(['status'=>BonusQi::STATUS_IS_END, 'end_at'=>time()], ['id'=>$id, 'status'=>BonusQi::STATUS_DEFAULT]);
        if ($update) {
            return $this->message('操作成功', $this->redirect(['index']), 'success');
        } else {
            return $this->message('状态不正确', $this->redirect(['index']), 'error');

        }
    }

    /**
     * 分布奖
     * @author zen
     * @DateTime 2020-08-21T16:21:23+0800
     * @return   [type]                   [description]
     */
    public function actionDp()
    {
        $model = new DpForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($model->reset()) {
                return $this->message('设置成功', $this->refresh(), 'success');
            }
        }
        // $model->calc(); // 预算

        $searchModel = new SearchModel([
            'model' => BonusDp::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query;

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'model' => $model,
        ]);
    }

    public function actionDpCalc($id)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $update = BonusDp::updateAll(['status'=>BonusDp::STATUS_IS_END, 'calc_at'=>time()], ['id'=>$id, 'status'=>BonusDp::STATUS_DEFAULT]);
            if (!$update) {
                throw new \Exception('状态不正确', 1);
            }
            $res = Bonus::duiPeng();
            $update = BonusDp::updateAll(['bonus'=>$res['bonus'],'tax'=>$res['tax'],'fee'=>$res['fee'],'payment'=>$res['payment']], ['id'=>$id]);
            if (!$update) {
                throw new \Exception('结算信息保存失败', 1);
            }
            $transaction->commit();
            return $this->message('结算成功', $this->redirect(['dp']), 'success');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->message($e->getMessage(), $this->redirect(['dp']), 'error');
        }
    }

    public function actionBb()
    {
        $yeji = BonusYear::find()->sum('sales');
        if (!$yeji) {
            $yeji = 0;
        }
        $bs = BonusQi::find()->select('sum(bonus_7) as hj, sum(payment) as sf, sum(tax) as tax, sum(fee) as fee')->asArray()->one();
        if (!$bs) {
            $bs = [
                'hj' => 0,
                'sf' => 0,
                'tax' => 0,
                'fee' => 0,
            ];
        }
        // 减去合计和实发
        $payment = Bonus::find()->where(['in', 'bonus_type', [4,5]])->sum('payment');
        $amount = Bonus::find()->where(['in', 'bonus_type', [4,5]])->sum('amount');
        $tax = Bonus::find()->where(['in', 'bonus_type', [4,5]])->sum('tax');
        $fee = Bonus::find()->where(['in', 'bonus_type', [4,5]])->sum('fee');
        $bs['hj'] -= $amount;
        $bs['sf'] -= $payment;
        $bs['tax'] -= $tax;
        $bs['fee'] -= $fee;

        $bs['yeji'] = $yeji;
        $bs['bs'] = [];
        for ($i=1; $i < 4; $i++) {
            $bonusName = Bonus::$typeArr[$i]; 
            $bl = 0;
            $amount = Bonus::find()->where(['bonus_type'=>$i])->sum('payment');
            if (!$amount) {
                $amount = 0;
            } else {
                if ($bs['yeji'] > 0) {
                    // $bl = intval($amount / $bs['sf'] * 10000) / 100;
                    $bl = intval($amount / $bs['yeji'] * 10000) / 100;
                } else {
                    $bl = '-';
                }
            }
            $bs['bs'][] = [
                'name' => $bonusName,
                'amount' => $amount,
                'bl' => $bl,
            ];
        }
        

        $fx = BonusXf::find()->select('sum(ye_ji) as yeji, sum(bonus) as hj, sum(tax) as tax, sum(payment) as sf, sum(fee) as fee')->asArray()->one();
        if (!$fx) {
            $fx = [
                'ye_ji' => 0,
                'hj' => 0,
                'sf' => 0,
                'tax' => 0,
                'fee' => 0,
            ];
        }
        return $this->render($this->action->id, ['bs'=>$bs, 'fx'=>$fx]);
    }


    public function actionXf()
    {
        $searchModel = new SearchModel([
            'model' => BonusXf::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query;

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionXfCalc($id)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $update = BonusXf::updateAll(['status'=>BonusXf::STATUS_IS_END, 'calc_at'=>time()], ['id'=>$id, 'status'=>BonusXf::STATUS_DEFAULT]);
            if (!$update) {
                throw new \Exception('状态不正确', 1);
            }
            $res = Bonus::bonusShop();
            $update = BonusXf::updateAll(['bonus'=>$res['bonus'],'tax'=>$res['tax'],'fee'=>$res['fee'],'payment'=>$res['payment']], ['id'=>$id]);
            if (!$update) {
                throw new \Exception('结算信息保存失败', 1);
            }
            $transaction->commit();
            return $this->message('结算成功', $this->redirect(['xf']), 'success');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->message($e->getMessage(), $this->redirect(['xf']), 'error');
        }
    }

    public function actionFl()
    {
        $model = new FlForm();
        if ($model->load(Yii::$app->request->post())) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                if (!$model->calc()) {
                    throw new \Exception('结算失败', 1);
                }
                $transaction->commit();
                return $this->message('结算成功', $this->refresh(), 'success');
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->message($e->getMessage(), $this->refresh(), 'error');
            }
        }
        $searchModel = new SearchModel([
            'model' => BonusFl::class,
            'scenario' => 'default',
            // 'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query;

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'model' => $model,
        ]);
    }

    public function actionFour()
    {
        BonusQi::staticGetModel();
        $list = BonusQi::newFour();
        return $this->render($this->action->id, ['list'=>$list]);
    }

    public function actionCalcQi($id)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model = BonusQi::findOne($id);
            if (!$model || $model->status != BonusQi::STATUS_DEFAULT) {
                throw new \Exception('状态不正确', 1);
            }
            $update = BonusQi::updateAll(['status'=>BonusQi::STATUS_IS_END, 'end_at'=>time()], ['id'=>$model->id, 'status'=>BonusQi::STATUS_DEFAULT]);
            if (!$update) {
                throw new \Exception('结束当期失败', 1);
            }
            // 对碰奖
            $dp = BonusDp::addYeji();
            $update = BonusDp::updateAll(['status'=>BonusDp::STATUS_IS_END, 'calc_at'=>time()], ['id'=>$dp->id, 'status'=>BonusDp::STATUS_DEFAULT]);
            if (!$update) {
                throw new \Exception('分布奖状态不正确', 1);
            }
            $res = Bonus::duiPeng();
            $update = BonusDp::updateAll(['bonus'=>$res['bonus'],'tax'=>$res['tax'],'fee'=>$res['fee'],'payment'=>$res['payment']], ['id'=>$dp->id]);
            if (!$update) {
                throw new \Exception('分布奖结算信息保存失败', 1);
            }
            $clears = [];
            // 如果是第四期
            if ($model->id % 4 == 0) {
                // 结算复消奖金
                $xf = BonusXf::addYeji();
                $update = BonusXf::updateAll(['status'=>BonusXf::STATUS_IS_END, 'calc_at'=>time()], ['id'=>$xf->id, 'status'=>BonusXf::STATUS_DEFAULT]);
                if (!$update) {
                    throw new \Exception('复消奖状态不正确', 1);
                }
                $res = Bonus::bonusShop();
                $update = BonusXf::updateAll(['bonus'=>$res['bonus'],'tax'=>$res['tax'],'fee'=>$res['fee'],'payment'=>$res['payment']], ['id'=>$xf->id]);
                if (!$update) {
                    throw new \Exception('复消奖结算信息保存失败', 1);
                }
                // 释放复消奖
                // BonusDj::jieDong('bonus_4');
                // 释放合作奖
                // BonusDj::jieDong('bonus_3');
                $clears[] = 'bonus_4';
                $clears[] = 'bonus_3';
            }
            $clears[] = 'bonus_1';
            $clears[] = 'bonus_2';
            $clears[] = 'bonus_5';
            // BonusDj::jieDong('bonus_1'); // 释放分享奖
            // BonusDj::jieDong('bonus_2'); // 释放分布奖
            // BonusDj::jieDong('bonus_5'); // 释放福利奖
            Yii::$app->queue->push(new \common\queues\BonusClearJob(['clears'=>$clears]));
            $transaction->commit();
            return $this->message('结算成功', $this->redirect(['four']), 'success');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->message($e->getMessage(), $this->redirect(['four']), 'error');
        }
    }



}
